<?php

declare(strict_types=1);

namespace app\common\service\sys;

use app\common\dao\sys\MenuDao;
use app\common\traits\ServiceTrait;
use app\common\dao\sys\RoleDao;
use app\common\dao\sys\UserRoleDao;
use app\common\dao\sys\UserRoleMenusDao;

/**
 * 角色 - 业务
 * @author:kaige
 * @date:2022-06-13
 * @copyright ©2022 泉州市盛筑信息科技有限公司 版权所有
 */
class RoleService
{
  protected $dao = null;

  public function __construct()
  {
    $this->dao = new RoleDao();
  }
  use ServiceTrait;

  /**
   * 重写 列表条件
   */
  public function _list_where($post)
  {
    $where = [];
    if (isset($post['name']) && $post['name'] != "") {
      $where[] = ['name', 'like', '%' . $post['name'] . '%'];
    }
    $result['where'] = $where;
    $result['field'] = [];
    $result['order'] = ['create_time' => 'desc'];
    return $result;
  }

  /**
   * 取角色的操作权限数组
   * @param $id
   * @return array
   */
  public function getRoleMenuData($role_id, $user_id)
  {
    $result = _err();
    $info = $this->dao->getInfoById($role_id);
    if (!$info) {
      return _err('角色不存在');
    }
    if (!$user_id) {
      return _err('未登录');
    }
    $userRoleDao = new UserRoleMenusDao();
    $permList  = $userRoleDao->getListAll(['user_role_id' => $role_id]);
    if ($permList) {
      $nodeList = array_column($permList, 'menu_id');
    } else {
      $nodeList = [];
    }
    $menuService = new MenuService();
    $manageMenu = $menuService->getMenuDataTree($user_id, 2); //当前登陆者的后台菜单树,权限is_auth 第二参传2
    $result['data'] = $menuService->setUserRoleMenuDtree($manageMenu['menu'], $nodeList);
    $result['status'] = true;
    return $result;
  }

  /**
   * 获取用户角色权限
   */
  public function getRoleAuth($user_id)
  {
    if($user_id == config('kaige.super_id')){
      return ['roles' => ['ROOT'], 'perms' => []];
    }
    $menuDao = new MenuDao();
    $userRoleDao = new UserRoleDao();
    // 查角色,用户对应多角色
    $where = [];
    $where[] = ['user_id', '=', $user_id];
    $roles = $userRoleDao->getListAll($where); //找出所有绑定的角色
    $roles_code = [];
    $roles_id = [];
    if ($roles) {
      foreach ($roles as $v) {
        $roles_code[] = $v['code']; //角色代码加入数组 //角色代码 在前端为 权限名称
        $roles_id[] = $v['id'];
      }
    }
    $menulist = $menuDao->getRoleMenuData($roles_id,2);
    $perms = [];
    if($menulist){
      foreach($menulist as $val){
        if($val['menu_type'] == 3){
          $perms[] = $val['node'];
        }
      }
    }
    return ['roles' => $roles_code, 'perms' => $perms];
  }
}
